<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;

class Post extends Model
{
    protected $fillable = [
        'title',
        'body',
    ];

    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    /*public function addComment($body){
        $this->comments()->create(compact('body'));
    }*/

    public function addComment(Comment $comment)
    {
        $this->comments()->save($comment);
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public static function archives()
    {
        return static::selectRaw('year(created_at) year,monthname(created_at) month, count(*) published')
            ->groupBy('year', 'month')
            ->orderByRaw('min(created_at) desc')
            ->get();

    }

    public function scopeFilter($query, $value)
    {
        $month = $value['month'];
        if ($month) {
            $query->whereMonth('created_at', Carbon::parse($month)->month);
        }
        $year = $value['year'];
        if ($year) {
            $query->whereYear('created_at', $year);
        }
    }

}
